package threadlocal;

import java.util.concurrent.TimeUnit;

public class ThreadLocalDemo {

    private static ThreadLocal<String> threadLocal=new ThreadLocal<>();

    private static class MyThread implements Runnable{

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getId()+"线程开始工作...");
            threadLocal.set("我是线程"+Thread.currentThread().getId());
            try {
                TimeUnit.SECONDS.sleep(1);
                System.out.println(threadLocal.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                threadLocal.remove();
            }
        }
    }

    public static void main(String[] args) {
        threadLocal.set("我是线程"+Thread.currentThread().getId());
        new Thread(new MyThread()).start();
        System.out.println(threadLocal.get());
        threadLocal.remove();
    }
}
